<template>
	<view class="image-container" v-if="name" :style="{backgroundColor: bgCard}">
		<view class="img_info">
			<view class="logo_img">
				<image
					mode="aspectFit"
					@error="imgError()"
					lazy-load
					class="logo_img_"
					:src="`/static/network/card/${getImgCard(name) || 'card'}.png`"
				></image>
			</view>
			<view class="card_rigth">
				<p>{{ name }}</p>
				<p class="type_title">
					{{
						type == 4
							? '预付费卡'
							: type == 3
							? '准贷记卡'
							: type == 2
							? '信用卡'
							: '储蓄卡'
					}}
				</p>
				<p class="code_title" v-if="!showCode">
					<span class="tip">···</span>
					<span class="tip">···</span>
					<span class="tip">···</span>
					{{ code.slice(-4) }}
				</p>
				<p class="code_title" v-else>
					<template v-if="!isEye">
						<span class="tip">···</span>
						<span class="tip">···</span>
						<span class="tip">···</span>
						{{ code.slice(-4) }}
						<uni-icons
							style="margin-left: 12rpx"
							size="22"
							color="#fff"
							:type="isEye ? 'eye' : 'eye-slash'"
							@click="isEye = !isEye"
						></uni-icons>
					</template>
					<template v-else>
						{{ code.replace(/(.{4})/g, '$1 ') }}
						<uni-icons
							style="margin-left: 12rpx"
							size="22"
							color="#fff"
							:type="isEye ? 'eye' : 'eye-slash'"
							@click="isEye = !isEye"
						></uni-icons>
					</template>
				</p>
			</view>
		</view>
		<img
			:ref="(el) => setRef(el, refName)"
			style="width: 100%; display: none"
			:src="`/static/network/card/${getImgCard(name) || 'card'}.png`"
			alt="My Image"
			@load="getMainColor()"
		/>
	</view>
</template>

<script setup lang="ts">
	import {ref, onMounted, toRefs, nextTick} from 'vue';
	import apiAccount from '@/util/network_api/account.js';
	import {onUnload, onLaunch, onLoad, onHide, onShow} from '@dcloudio/uni-app';
	import logoCard from '@/util/card_tool/card_logo_name.json';
	onUnload(() => {
		uni.hideLoading();
	});
	const props = defineProps({
		// 子元素标识（如在同一页面中调用多次组件，此参数不可重复）
		refName: String,
		// 银行卡名称
		name: String,
		// 加密的卡号
		code: String,
		type: {
			type: Number,
			default: 1,
		},
		showCode: {
			type: Boolean,
			default: false,
		}, //是否查看卡号
		backgroundColor: {
			type: String,
			default: () => '',
		},
	});
	const {refName, name, code, type, showCode} = toRefs(props);
	const emits = defineEmits(['close']);
	const bgCard = ref('rgb(0,124,255)');
	const refMap = ref({}); //ref
	const setRef = (el, str) => {
		nextTick(() => {
			if (el) {
				refMap.value[`${str}`] = el;
			}
		});
	};
	const isEye = ref(false);
	const getMainColor = () => {
		const img = refMap.value[refName.value]; // 通过ref属性获取到图片元素
		const canvas = document.createElement('canvas'); // 创建画布对象
		const context = canvas.getContext('2d'); // 获取上下文
		canvas.width = img.naturalWidth || img.clientWidth; // 设置画布大小为图片原始宽度或者客户区域宽度（如果未定义）
		canvas.height = img.naturalHeight || img.clientHeight; // 设置画布高度为图片原始高度或者客户区域高度（如果未定义）
		context.drawImage(img, 0, 0); // 将图片绘制到画布上
		img.crossOrigin = ''; //防止跨域报错不能使用，但依然会报错
		const imageData = context.getImageData(
			0,
			0,
			canvas.width,
			canvas.height,
		).data; // 获取图像数据

		let rTotal = 0;
		let gTotal = 0;
		let bTotal = 0;
		for (let i = 0; i < imageData.length; i += 4) {
			rTotal += imageData[i];
			gTotal += imageData[i + 1];
			bTotal += imageData[i + 2];
		}

		const totalPixels = imageData.length / 4;
		const avgR = Math.round(rTotal / totalPixels);
		const avgG = Math.round(gTotal / totalPixels);
		const avgB = Math.round(bTotal / totalPixels);
		bgCard.value = `rgb(${avgR}, ${avgG}, ${avgB})`;
		if (props.backgroundColor) {
			bgCard.value = props.backgroundColor
		}
	};
	const isdefault = ref(false); //默认
	const getImgCard = (n) => {
		for (let key in logoCard) {
			let item = logoCard[key];
			if (item == n) {
				isdefault.value = false;
				return key;
			}
		}
	};

	const imgError = () => {
		isdefault.value = true;
	};
</script>
<style lang="scss" scoped>
	.image-container {
		height: 240rpx;
		background-color: rgb(0, 124, 255);
		padding: 30rpx;
		box-sizing: border-box;
		margin-bottom: 24rpx;
		border-radius: 10rpx;
		display: flex;
		flex-direction: column;
		gap: 24rpx;

		.img_info {
			display: flex;
			gap: 12rpx;

			.logo_img {
				width: 40rpx;
				height: 40rpx;
				background-color: #fff;
				border-radius: 50%;
				.logo_img_ {
					width: 100%;
					height: 100%;
				}
			}

			.card_rigth {
				flex: 1;
				color: #fff;
				font-size: 30rpx;
				display: flex;
				flex-direction: column;
				gap: 6rpx;

				.type_title {
					font-size: 26rpx;
				}
			}
		}

		.code_title {
			color: #fff;
			flex: 1;
			display: flex;
			gap: 12rpx;
			align-items: center;
			// justify-content: center;
			font-size: 40rpx;
			margin-top: 30rpx;

			.tip {
				font-weight: bold;
				// letter-spacing: .5rem;
			}
		}
	}
</style>
